import request from 'request';
import crypto from 'crypto';
import uuid from 'uuid';
const baiduApikey = '7g6jBHGcj6d3g07a2mbSRVrrlyT6ofrp';
const baiduApiSecret = 'XGV7QWjESfBo6vAFDX9oEI6BF2ze33ng';
import {exesql} from '../database/db';


// 构建Post请求
function baiduGetOptions(path, baiduAccessToken) {
    const options = {
        headers: {
            "Connection": "close",
            'X-IOT-APP': baiduApikey,
            'X-IOT-Signature': getSignature(path, baiduAccessToken),
            'X-IOT-Signature-Type': 'Web',
            'X-IOT-Token': baiduAccessToken
        },
        url: 'https://openapi-iot.baidu.com' + path,
        method: 'GET',
        timeout: 10000,
    };
    return options;
}

function randomString(len) {
    let id = uuid.v1()
    id = id.replace(/-/g, "");
    return id;
}

 // 签名
 function getSignature(uri, baiduAccessToken) {
    let nonce = randomString(16);
    let sha1 = crypto.createHash('sha1');
    let signature = nonce + baiduApikey + baiduApiSecret + baiduAccessToken + uri;
    sha1.update(nonce);
    sha1.update(baiduApikey);
    sha1.update(baiduApiSecret);
    sha1.update(baiduAccessToken);
    sha1.update(uri);

    let signaturestr = sha1.digest('hex');
    signaturestr = nonce + ':' + signaturestr;
    return signaturestr;
}

// 查询无效的专辑
function queryAlllbum(router) {
    return exesql('SELECT album_id,name FROM album',[]);
}

function sleep(seconds) {
    return new Promise(function (resolve, reject) {
        setTimeout(() => {
            resolve();
        }, seconds);
    })
}

function getBaiduAlbumInfo(deviceUuid, albumid,baiduToken) {
    let path = '/v2/audio/tracklist?albumid=' + albumid + '&orderby=asc&page=1&psize=10&upid=0&deviceUuid=' + deviceUuid;
    path = encodeURI(path);
    const options = baiduGetOptions(path, baiduToken);
    return new Promise(function(resolve, reject) {
        request(options, function (error, response, data) {
            return resolve({ err: error, data: data });
        });
    })
}

// 更新专辑图片(优先用middle，如果middle为空，用large)
export async function updateAlbumImage(){
    try {
        const { err, result } = await queryAlllbum('query');
        if (err) {
            console.log(err);
            return;
        }
        if (result && result.length  > 0) {
            for (let index = 0,len = result.length; index < len; index++) {
                const album = result[index];
                const {err, data } = await getBaiduAlbumInfo('0e450000000008',album.album_id,'135c3b305ea011e899f381550a477681');
                if (err) {
                    console.log(err);
                    return;
                }
                const json = JSON.parse(data);
                if (parseInt(json.status,10) === 0 && parseInt(json.data.total,10) > 0) {
                    // 更新专辑信息
                    if (json.data.list && json.data.list.length) {
                       const item = json.data.list[0];
                        let middle = '';
                        if (item.cover_url) {
                            middle = item.cover_url.middle || item.cover_url.large;
                        }
                        console.log(`album_id:${album.album_id} -> ${middle}`);
                        if (middle) {
                            const {err, result} = await exesql('UPDATE `album` SET `img_url` = ? WHERE album_id= ?;',[middle,album.album_id ]);
                            if (err) {
                                console.log(`album_id:${album.album_id},`, err);
                                break;
                            }
                        }
                    }
                    await sleep(2000);
                }
            }
        }

    } catch (error) {
        console.log('try:', error);
    }
}

// updateAlbumImage();

getBaiduAlbumInfo('0e450000000008', 56780734066,"135c3b305ea011e899f381550a477681").then(function(data){
    console.log(data.data);

});

